package com.cskaoyan.service.impl;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.FeedbackVo;
import com.cskaoyan.mapper.MarketFeedbackMapper;
import com.cskaoyan.model.MarketFeedback;
import com.cskaoyan.model.MarketUser;
import com.cskaoyan.service.FeedbackService;
import com.cskaoyan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class FeedbackServiceImpl implements FeedbackService {
    @Autowired
    MarketFeedbackMapper marketFeedbackMapper;

    @Autowired
    UserService userService;

    //使用正则表达式来对手机号的格式和参数进行验证
    private static final String PHONE_PATTERN = "^1[3-9]\\d{9}$";


    @Override
    public BaseRespVo submit(FeedbackVo feedbackVo, Integer userId) {
        /*方式一：
        //手机号不是11位数字会发生参数错误:errmeg:参数不对 errno：401
        //位数不为11会发生错误
        if(feedbackVo.getMobile().length() != 11){
            return BaseRespVo.badArgumentValue();
        }
        for (char c : feedbackVo.getMobile().toCharArray()) {
            if(!Character.isDigit(c)){
                //所传数据中不是数字会发生参数错误
                return BaseRespVo.badArgumentValue();
            }
        }*/

        //方式二
        Pattern pattern = Pattern.compile(PHONE_PATTERN);
        Matcher matcher = pattern.matcher(feedbackVo.getMobile());
        if (!matcher.matches()) {
            return BaseRespVo.badArgumentValue();
        }

        Date current = new Date();
        //通过userId查询userName
        MarketUser marketUser = userService.findById(userId);
        //构建marketFeedback,插入到数据库中
        MarketFeedback marketFeedback =MarketFeedback.builder()
                .userId(userId)
                .username(marketUser.getUsername())
                .mobile(feedbackVo.getMobile())
                .feedType(feedbackVo.getFeedType())
                .content(feedbackVo.getContent())
                .status(1)
                .hasPicture(feedbackVo.getHasPicture())
                .picUrls(feedbackVo.getPicUrls())
                .addTime(current)
                .updateTime(current)
                .deleted(false)
                .build();
        marketFeedbackMapper.insertSelective(marketFeedback);

        return BaseRespVo.ok(null);
    }
}
